package com.moetube.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.moetube.search.pojo.VideoInfo;
import com.moetube.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 按照查询条件进行数据查询
     */
    @Override
    public Map search(Map<String, String> searchMap) {

        //0.创建返回结果resultMap
        Map<String,Object> resultMap=new HashMap<>();

        //1.判断是否有查询条件
        if(searchMap!=null&&searchMap.size()>0) {

            //2.构建查询条件封装对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            //2.1按照关键字查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
                boolQueryBuilder.must(QueryBuilders.matchQuery("title", searchMap.get("keywords")).operator(Operator.AND));
            }
            //2.2按照一级分类id过滤
            if(StringUtils.isNotEmpty(searchMap.get("tids_1"))){
                boolQueryBuilder.filter(QueryBuilders.termsQuery("category1Id",searchMap.get("tids_1")));
            }
            //2.3按照二级分类id过滤
            if(StringUtils.isNotEmpty(searchMap.get("tids_2"))){
                boolQueryBuilder.filter(QueryBuilders.termsQuery("category2Id",searchMap.get("tids_2")));
            }

            //2.4按照时间进行区间过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("time"))){
                String[] prices = searchMap.get("time").split("-");
                // 0-500 500-1000
                if (prices.length == 2){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("videoTime").lte(Integer.parseInt(prices[1])*60));
                }
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("videoTime").gte(Integer.parseInt(prices[0])*60));
            }

            //封装完查询条件对象
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

            //开启分页
            //获取当前页码和条数
            String pageNum = searchMap.get("pageNum");
            String pageSize = searchMap.get("pageSize");
            if(StringUtils.isEmpty(pageNum)){
                pageNum="1";
            }
            if(Integer.parseInt(pageNum)<0){
                throw new RuntimeException("请求参数有误");
            }
            if(StringUtils.isEmpty(pageSize)){
                pageSize="20";
            }
            if(Integer.parseInt(pageSize)<0){
                throw new RuntimeException("请求参数有误");
            }
            //设置分页
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));

            //按照相关字段进行排序查询
            // 1.当前域 2.当前的排序操作(升序ASC,降序DESC)

            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if ("ASC".equals(searchMap.get("sortRule"))){
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                }else if("DESC".equals(searchMap.get("sortRule"))){
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            //设置高亮域以及高亮的样式
            HighlightBuilder.Field field = new HighlightBuilder.Field("title")//高亮域
                    .preTags("<span style='color:red'>")//高亮样式的前缀
                    .postTags("</span>");//高亮样式的后缀
            nativeSearchQueryBuilder.withHighlightFields(field);

            //3.开启查询
            /**
             *第一个参数：条件构建对象
             * 第二个参数：查询操作的实体类
             * 第三个参数：查询结果操作对象
             */
            AggregatedPage<VideoInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), VideoInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //查询结果操作
                    //3.1获取查询结果,并添加到新创建的list集合中
                    List<T> list = new ArrayList<>();

                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            VideoInfo videoInfo = JSON.parseObject(hit.getSourceAsString(), VideoInfo.class);

                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if(highlightFields!=null&&highlightFields.size()>0){
                                videoInfo.setTitle(highlightFields.get("title").getFragments()[0].toString());
                            }
                            //把每个videoInfo对象放到list集合中
                            list.add((T) videoInfo);

                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });

            //4.封装最终的返回结果
            //4.1添加总的记录数
            resultMap.put("total", resultInfo.getTotalElements());
            //4.2添加总的页数
            resultMap.put("totalPage", resultInfo.getTotalPages());
            //4.3添加最终的查询结果
            resultMap.put("rows", resultInfo.getContent());

            //当前页
            resultMap.put("pageNum",pageNum);
            return resultMap;
        }
        return null;
    }
}
